package sample;

import bean.GroupInfo;
import bean.ImageInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import utils.fileHandler.FileHandler;
import utils.groupsInfoHandler.GroupsInfoHandler;
import utils.screenCtrl.ScreenCtrlLinux;
import utils.screenCtrl.WindowStatus;
import utils.shortcutKey.ShortcutKey;
import utils.wallpaperCtrl.WallpaperCtrlUKUILinux;
import utils.wallpaperHandler.WallpaperHandler;
import webView.WebViewCtrl;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;


public class Controller implements Initializable {
    public TextField quickkey;
    public Button kuaijie;
    public FlowPane screenGridPane;
    public FlowPane autoGridPane;
    public AnchorPane rootPane;
    public TabPane wholeTapPane;
    public Label searchImage;
    public ListView<ImageView> groupListView;
    public ImageView prePaperImage;
    public ScrollPane scrollGrid;
    public FlowPane flowPane;
    public TextField searchField;
    public Label name;
    public ComboBox<String> groupComboBox;
    public Button saveKeyBButton;
    public HBox hBoxMid2;
    public Button saveGroupButton;
    public Label groupNameLabel;
    public Tab wallpaperTab;
    public TextField groupNameField;
    public Label keyBLabel;
    public Button addWallpaperButton;
    public Button deleteWallpaperButton;
    public Button webViewButton;
    public Pane preViewPane;
    public MediaView preMediaView;
    public Tab splitScreenTab;
    public ScrollPane scpp;
    public ScrollPane scppp;
    public VBox preHelpVbox;

    public int flag = 1;
    public List<ImageInfo> imageInfoList;
    public HashMap<String, ImageInfo> imageInfoHashMap;
    public List<String> kebStr;//记录每次设置的壁纸快捷键
    public GroupInfo groupInfoStatic;//当前选中的group
    public VBox preImageVbox;
    public VBox preMediaVbox;


    private boolean mediaPlayStatue;

    private String Path;
    public Scene scene = new Scene(new Group());
    private ArrayList<KeyCombination> quickKeyList;
    private ArrayList<String> quickKeyNameList;
    private ArrayList<String> screenNameList;
    private List<WindowStatus> selectWindows;
    private String[] quickStr;
    private KeyCombination.Modifier[] combinationCouple;
    private KeyCode combinationKey;
    public static String screenName;
    public WebView helpView;

    public void flashGroupComboBox() {
        ObservableList<String> groupComboBoxList = FXCollections.observableArrayList();
        if (groupComboBox.getItems().size() != 0) {
            groupComboBox.getItems().remove(0, groupComboBox.getItems().size());
        }
        groupComboBoxList.add("新建壁纸组别");
        if (GroupsInfoHandler.getGroupsNumber() == 0) {
            groupNameLabel.setText("未设置壁纸组别");
        } else {
            groupComboBoxList.addAll(GroupsInfoHandler.getGroupsName());
        }
        groupComboBox.getItems().addAll(groupComboBoxList);
        //为 groupComboBox 添加监听
        groupComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String old_v, String new_v) {
                groupNameLabel.setText(new_v);
                ObservableList<ImageView> imageViewObservableList = FXCollections.observableArrayList();

                Set<String> groupsName = GroupsInfoHandler.getGroupsObject().keySet();
                for (String name : groupsName) {
                    if (name.equals(new_v)) {
                        groupNameField.setText(name);
                        GroupInfo groupInfo = GroupsInfoHandler.getGroupInfo(name);
                        keyBLabel.setText("");
                        //加载壁纸组别快捷键
                        for (String s : groupInfo.getKeyBoard()) {
                            keyBLabel.setText(keyBLabel.getText() + "-" + s);
                        }
                        //重置壁纸选中状态
                        for (ImageInfo imageInfo : imageInfoList) {
                            imageInfo.setCheckVF();
                        }
                        //加载壁纸组别预览 groupListView
                        WallpaperCtrlUKUILinux.wallpaperPlay.setGroupInfo(groupInfo);
                        for (String url : groupInfo.getImagePath()) {
                            if (new File(url.replace("file:", "")).exists()) {
                                ImageInfo imageInfo = imageInfoHashMap.get(url);
                                imageInfo.setCheckVT();
                                ImageView imageView = new ImageView(new Image(url, 300, 0, true, true, true));
                                double height = 120/*groupListView.getHeight()*/;
                                double width = height * 1.78;
                                imageView.setFitWidth(width);
                                imageView.setFitHeight(height);
                                imageViewObservableList.add(imageView);
                            }
                        }
                        break;
                    } else if (name.equals("新建壁纸组别")) {
                        //重置壁纸选中状态
                        for (ImageInfo imageInfo : imageInfoList) {
                            imageInfo.setCheckVF();
                        }
                        groupInfoStatic = null;
                    }
                }

                if (groupListView.getItems().size() != 0) {
                    for (ImageView item : groupListView.getItems()) {
                        item = null;
                    }
                    groupListView.getItems().remove(0, groupListView.getItems().size());
                }
                groupListView.setOrientation(Orientation.HORIZONTAL);
                groupListView.getItems().addAll(imageViewObservableList);
            }
        });
    }

    public void addImageToFlowPane(String imageUrls) {
        Image image = new Image("file:" + imageUrls, 300, 0, true, true, true);
        ImageInfo imageInfo = new ImageInfo(image);
        imageInfoList.add(imageInfo);
        imageInfoHashMap.put(image.getUrl(), imageInfo);
        addImageToFlowPane(imageInfo);
    }

    public void addImageToFlowPane(ImageInfo imageInfo) {
        double fitHeight = 130;//设置图像高度
        double fitWidth = 231.6;//设置图像宽度
        ImageView imageView = imageInfo.getImageView();
        imageView.setFitWidth(fitWidth);
        imageView.setFitHeight(fitHeight);
        imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                if(preHelpVbox.getChildren().size()==1){
                    preHelpVbox.getChildren().remove(0);
                }
                if (imageInfo.getType() == ImageInfo.SimpleImage) {
                    WallpaperCtrlUKUILinux.exitLiveWallpaperStatic();
                    String hDImagePath = WallpaperHandler.gethDImagePath(imageInfo.getImagePath().replace("file:", ""));
                    prePaperImage.setImage(new Image("file:" + hDImagePath, false));
                    preMediaView.setVisible(false);
                    preHelpVbox.setVisible(false);
                    preImageVbox.setVisible(true);
                    preMediaVbox.setVisible(false);
                    preMediaView.setMediaPlayer(null);
                    prePaperImage.setVisible(true);
                    WallpaperCtrlUKUILinux.setPictureWallpaperStatic(hDImagePath);
                } else if (imageInfo.getType() == ImageInfo.GifImage) {
                    /////////
                } else if (imageInfo.getType() == ImageInfo.VideoImage) {
                    WallpaperCtrlUKUILinux.setPictureWallpaperStatic(FileHandler.getBlackBackGroundImage());
                    WallpaperCtrlUKUILinux.exitLiveWallpaperStatic();
                    String hdVideoPath = WallpaperHandler.gethDVideoPath(imageInfo.getImagePath().replace("file:", ""));
                    System.out.println(hdVideoPath);
                    MediaPlayer mediaPlayer = new MediaPlayer(new Media("file:" + hdVideoPath));
                    mediaPlayer.stop();
                    mediaPlayStatue =false;
                    preMediaView.setMediaPlayer(mediaPlayer);
                    preMediaView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent mouseEvent) {
                            if (mediaPlayStatue){
                                mediaPlayer.stop();
                                mediaPlayStatue=false;
                            }else {
                                mediaPlayer.play();
                                mediaPlayStatue=true;
                            }
                        }
                    });
                    prePaperImage.setVisible(false);
                    preImageVbox.setVisible(false);
                    preHelpVbox.setVisible(false);
                    preMediaVbox.setVisible(true);
                    preMediaView.setVisible(true);
                    try {
                        WallpaperCtrlUKUILinux.setLiveWallpaperStatic(hdVideoPath,FileHandler.getTransparency(),FileHandler.getAudio());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        CheckBox checkBox = imageInfo.getCheckBox();
        checkBox.setLayoutX(0);
        checkBox.setLayoutY(0);
        Pane pane = new Pane();
        pane.setPrefWidth(fitWidth);
        pane.setPrefHeight(fitHeight);
        pane.getChildren().add(imageView);
        pane.getChildren().add(checkBox);
        flowPane.getChildren().add(pane);
        scrollGrid.setContent(flowPane);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        helpView=new WebView();
        helpView.setVisible(true);
        WebEngine engine = helpView.getEngine();
        engine.load(Objects.requireNonNull(Main.class.getClassLoader().getResource("helpInfo.html")).toString());

        kebStr = new ArrayList<>();
        imageInfoList = new ArrayList<>();
        imageInfoHashMap = new HashMap<>();

        //设置壁纸与分屏状态下的默认大小
        wholeTapPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
            @Override
            public void changed(ObservableValue<? extends Tab> observableValue, Tab old_tab, Tab new_tab) {
                if (new_tab.getId().equals(splitScreenTab.getId())) {
                    Main.setPrimaryStageHW(800, 1000);
                } else {
                    Main.setPrimaryStageHW(970, 2010);
                }
            }
        });

        preHelpVbox.getChildren().add(helpView);

        //读入静态壁纸文件(包括GIF动图) 构造 imageInfoList imageInfoHashMap
        File file = new File(FileHandler.getPreImageDirAbsolutePath());
        if (file.exists()) {
            File[] files = file.listFiles();
            assert files != null;
            for (int i = 0; i < files.length; i++) {
                ImageInfo imageInfo = new ImageInfo(new Image("file:" + files[i].getAbsolutePath(), 300, 0, true, true, true));
                imageInfoList.add(imageInfo);
                imageInfoHashMap.put(imageInfo.getImagePath(), imageInfo);
            }
        }

        //读入动态壁纸文件 构造 imageInfoList imageInfoHashMap
        file = new File(FileHandler.getPreVideoDirAbsolutePath());
        if (file.exists()) {
            File[] files = file.listFiles();
            assert files != null;
            for (int i = 0; i < files.length; i++) {
                ImageInfo imageInfo = new ImageInfo(new Image("file:" + files[i].getAbsolutePath(), 300, 0, true, true, true), ImageInfo.VideoImage);
                imageInfoList.add(imageInfo);
                imageInfoHashMap.put(imageInfo.getImagePath(), imageInfo);
            }
        }

        for (ImageInfo imageInfo : imageInfoList) {
            System.out.println(imageInfo.getImagePath());
        }

        //加载 flowPane 界面
        flowPane.setHgap(10);
        flowPane.setVgap(10);
        for (ImageInfo imageInfo : imageInfoList) {
            addImageToFlowPane(imageInfo);
        }
        //设置flowPane滑动属性
        scrollGrid.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        scrollGrid.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);

        flashGroupComboBox();//加载 GroupComboBox


        scpp.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scppp.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        Path = FileHandler.getRootPath()+"source/";
        screenName = null;
        quickStr = new String[3];
//        combinationCouple = new KeyCombination.Modifier[2];
//        quickKeyList = new ArrayList<KeyCombination>();
//        quickKeyNameList = new ArrayList<String>();
        screenNameList = new ArrayList<String>();
        selectWindows = new ArrayList<WindowStatus>();
        //加载分屏模块
        file = new File(Path + "spiltScreenRecord.txt");
        if (file.exists() == false) {
            PrintStream ps = null;
            try {
                ps = new PrintStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ps.println("0");
            ps.close();
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            String linenum = br.readLine();
            if (linenum != null) {
                int lineNum = Integer.valueOf(linenum);
                if (lineNum != 0) {
                    String str;
                    for (int i = 0; i < lineNum; i++) {
                        str = br.readLine();
                        screenNameList.add(str);
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //加载快捷键设置
        ShortcutKey.loadShortcutKey();
        //添加鼠标监听
        new MouseListener();
        ScreenSpilt ssp1 = new ScreenSpilt("spiltScrean_cross");
        this.screenGridPane.getChildren().add(ssp1);

        ScreenSpilt ssp2 = new ScreenSpilt("spiltScrean_half1");
        this.screenGridPane.getChildren().add(ssp2);

        ScreenSpilt ssp3 = new ScreenSpilt("spiltScrean_half2");
        this.screenGridPane.getChildren().add(ssp3);

        ScreenSpilt ssp4 = new ScreenSpilt("spiltScrean_three1");
        this.screenGridPane.getChildren().add(ssp4);

        ScreenSpilt ssp5 = new ScreenSpilt("spiltScrean_three2");
        this.screenGridPane.getChildren().add(ssp5);

        ScreenSpilt ssp6 = new ScreenSpilt("spiltScrean_three3");
        this.screenGridPane.getChildren().add(ssp6);

        ScreenSpilt ssp7 = new ScreenSpilt("spiltScrean_threeSpiltDown");
        this.screenGridPane.getChildren().add(ssp7);

        ScreenSpilt ssp8 = new ScreenSpilt("spiltScrean_threeSpiltUp");
        this.screenGridPane.getChildren().add(ssp8);

        ScreenSpilt ssp9 = new ScreenSpilt("spiltScrean_twoSpilt");
        this.screenGridPane.getChildren().add(ssp9);

        ScreenSpilt ssp10 = new ScreenSpilt("spiltScrean_twoSpiltRight");
        this.screenGridPane.getChildren().add(ssp10);

        addScreenSpiltRightListener(ssp1);
        addScreenSpiltRightListener(ssp2);
        addScreenSpiltRightListener(ssp3);
        addScreenSpiltRightListener(ssp4);
        addScreenSpiltRightListener(ssp5);
        addScreenSpiltRightListener(ssp6);
        addScreenSpiltRightListener(ssp7);
        addScreenSpiltRightListener(ssp8);
        addScreenSpiltRightListener(ssp9);
        addScreenSpiltRightListener(ssp10);

        File file01 = new File(Path + "spiltScreenRecord.txt");
        if (!file01.exists()) {
            PrintStream ps = null;
            try {
                ps = new PrintStream(file01);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ps.println("0");
            ps.close();
        }
        br = null;
        try {
            br = new BufferedReader(new FileReader(file01));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            String linenum = br.readLine();

            if (linenum != null) {
                int lineNum = Integer.valueOf(linenum);
                flag = lineNum;

                if (lineNum != 0) {
                    String str;
                    for (int i = 0; i < lineNum; i++) {
                        str = br.readLine();
                        ScreenSpilt sspi = new ScreenSpilt(str);
                        addScreenSpiltRightListener(sspi);
                        this.autoGridPane.getChildren().add(sspi);
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void addWallpaper(ActionEvent actionEvent) {//有bug未修改
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择添加的壁纸");
        Stage stage = new Stage();
        File file = fileChooser.showOpenDialog(stage);
        File newFile;
        if (FileHandler.getFileType(file.getPath()).equals("mp4")) {
            newFile = new File(FileHandler.gethDVideoDirAbsolutePath() + File.separator + file.getName());
        } else {
            newFile = new File(FileHandler.gethDImageDirAbsolutePath() + File.separator + file.getName());
        }
        //如果出现重复名称文件，则加上附件标签
        if (newFile.exists()) {
            String strPath = newFile.getParent();
            strPath = strPath + File.separator + newFile.getName();
            strPath = strPath.replace(".", "-副件.");
            newFile = new File(strPath);
        }
        try {
            Files.copy(file.toPath(), newFile.toPath());

            String preImageUrl = WallpaperChecker.createPreImage(newFile.getPath());
            WallpaperHandler.save();
            addImageToFlowPane(preImageUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void saveGroupButton(ActionEvent actionEvent) {
        GroupInfo groupInfo = new GroupInfo();
        String groupName = groupNameField.getText();
        ArrayList<String> imagePath = new ArrayList<>();
        for (ImageInfo imageInfo : imageInfoList) {
            if (imageInfo.getCheckSelect()) imagePath.add(imageInfo.getImagePath());
        }
        groupInfo.setImagePath(imagePath);
        groupInfo.setNumber(imagePath.size());
        groupInfo.setKeyBoard(kebStr);
        System.out.println(groupInfo + groupName);

        if (groupInfoStatic == null) {//新建壁纸组别
            GroupsInfoHandler.addNewGroup(groupName, groupInfo);
        } else {//更新壁纸组别
            GroupsInfoHandler.updateGroup(groupName, groupInfo);
        }
        GroupsInfoHandler.save();
        flashGroupComboBox();
        Main.flash();
    }

    @FXML
    public void getWebView(ActionEvent actionEvent) {
        Main.popUpWindow(WebViewCtrl.class, "webView");
    }

    @FXML
    public void deleteWallpaper(ActionEvent actionEvent) {
        for (int i = 0; i < imageInfoList.size(); i++) {
            ImageInfo imageInfo = imageInfoList.get(i);
            if (imageInfo.getCheckSelect()) {
                if (imageInfo.getType() == ImageInfo.SimpleImage) {
                    boolean deletePreFile = FileHandler.deleteFile(imageInfo.getImageAbsolutePath());
                    boolean deleteHdFile = FileHandler.deleteFile(WallpaperHandler.gethDImagePath(imageInfo.getImageAbsolutePath()));
                    WallpaperHandler.delete(imageInfo.getImageAbsolutePath(), WallpaperHandler.preImageType);
                } else if (imageInfo.getType() == ImageInfo.VideoImage) {
                    boolean deletePreFile = FileHandler.deleteFile(imageInfo.getImageAbsolutePath());
                    boolean deletehDFile = FileHandler.deleteFile(WallpaperHandler.gethDVideoPath(imageInfo.getImageAbsolutePath()));
                    WallpaperHandler.delete(imageInfo.getImageAbsolutePath(), WallpaperHandler.preVideoType);
                }
                imageInfoHashMap.remove(imageInfo.getImagePath());
                ImageInfo remove = imageInfoList.remove(i);
            }
        }
        removeImageFromFlowPane();
    }

    public void removeImageFromFlowPane() {
        for (int i = 0; i < flowPane.getChildren().size(); i++) {
            Pane pane = (Pane) flowPane.getChildren().get(i);
            CheckBox checkBox = (CheckBox) pane.getChildren().get(1);
            if (checkBox.isSelected()) {
                pane.getChildren().removeAll();
                flowPane.getChildren().remove(i);
            }
        }
    }

    @FXML
    public void saveKeyB(ActionEvent actionEvent) {
        keyBLabel.setText("请输入快捷键,按回车结束");
        kebStr = new ArrayList<>();
        saveKeyBButton.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                if (!keyEvent.getCode().getName().equals("Enter")) {
                    kebStr.add(keyEvent.getCode().getName());
                    String ss = "";
                    for (String s : kebStr) {
                        ss = ss + "-" + s;
                    }
                    keyBLabel.setText(ss);
                }
            }
        });
    }


    //imageView的button控件添加action事件
    public void spiltScreen(ActionEvent actionEvent) throws IOException {
        Button handle = (Button) actionEvent.getSource();
        Rectangle2D rectangle = CantSee.getRectangle();
        Stage stage = CantSee.getStage();
        File file = new File(Path + handle.getId() + ".txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String str;
        String[] strs;
        while ((str = br.readLine()) != null) {
            strs = str.split("#");
            CantSee.addFrame(Double.valueOf(strs[0]), Double.valueOf(strs[1]), Double.valueOf(strs[2]), Double.valueOf(strs[3]));
        }

        stage.show();
    }


    //buyongguan
    public void spiltScreen_quickkey(String name) throws IOException {
        Rectangle2D rectangle = CantSee.getRectangle();
        Stage stage = CantSee.getStage();
        File file = new File(Path + name + ".txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String str;
        String[] strs;
        while ((str = br.readLine()) != null) {
            strs = str.split("#");
            CantSee.addFrame(Double.valueOf(strs[0]), Double.valueOf(strs[1]), Double.valueOf(strs[2]), Double.valueOf(strs[3]));
        }
        stage.show();
    }

    public void takePhoto() throws Exception {
        List<WindowStatus> allWindow = ScreenCtrlLinux.getAllWindowStatusStatic();
        List<WindowStatus> selectWindows = new ArrayList<WindowStatus>();
        for (int i = 0; i < allWindow.size(); i++) {
            System.out.println(allWindow.get(i).getName());
        }
        //DrawSplitScreenImageGraphics2D.drawImageStatic("/home/fds/test.png",allWindow,ScreenCtrlLinux.getDeskWindowStatusStatic());
    }

    public void putinkey(KeyEvent keyEvent) {//快捷键输入框
        if (screenName == null) {
            keyEvent.consume();
            return;
        }

        switch (keyEvent.getCode()) {
            case A:
            case B:
            case C:
            case D:
            case E:
            case F:
            case G:
            case H:
            case I:
            case J:
            case K:
            case L:
            case M:
            case N:
            case O:
            case P:
            case Q:
            case R:
            case S:
            case T:
            case U:
            case V:
            case W:
            case X:
            case Y:
            case Z:
                quickStr[2] = keyEvent.getCode().getName();
                break;
            case CONTROL:
                quickStr[0] = "control";
                break;
            case ALT:
                quickStr[1] = "alt";
                break;
            case SHIFT:
                quickStr[1] = "shift";
                break;
            case BACK_SPACE:
            case DELETE:
                System.out.println("delete");
                if (quickStr[2] != null) {
                    quickStr[2] = null;
                } else if (quickStr[1] != null) {
                    quickStr[1] = null;
                } else if (quickStr[0] != null) {
                    quickStr[0] = null;
                }
                break;
        }
        StringBuffer sb = new StringBuffer();
        if (quickStr[0] != null) {
            sb.append(quickStr[0]);
            if (quickStr[1] != null)
                sb.append(" + " + quickStr[1]);
            if (quickStr[2] != null)
                sb.append(" + " + quickStr[2]);
        } else {
            if (quickStr[1] != null) {
                sb.append(quickStr[1]);
                if (quickStr[2] != null)
                    sb.append(" + " + quickStr[2]);
            } else if (quickStr[2] != null) {
                sb.append(quickStr[2]);
            }
        }
        quickkey.setText(sb.toString());

        keyEvent.consume();
    }

    //shezhikuaijiejian
    public void setQuickKey(ActionEvent actionEvent) {
        Button button = (Button) actionEvent.getSource();
        if (screenName == null) {
            quickkey.setPromptText("请右键选择分屏");
            return;
        }
        if (quickStr[2] == null){
            quickkey.setPromptText("必须包含字母键");
            return;
        }
        String key;
        String unkey;
        if (quickStr[0] == null && quickStr[1] == null) {
            key = "pressed" + " " + quickStr[2];
            unkey = "released" + " " + quickStr[2];
        } else if (quickStr[0] != null && quickStr[1] == null) {
            key = quickStr[0] + " " + "pressed" + " " + quickStr[2];
            unkey = quickStr[0] + " " + "released" + " " + quickStr[2];
        } else if (quickStr[0] == null && quickStr[1] != null) {
            key = quickStr[1] + " " + "pressed" + " " + quickStr[2];
            unkey = quickStr[1] + " " + "released" + " " + quickStr[2];
        } else {
            key = quickStr[0] + " " + quickStr[1] + " " + "pressed" + " " + quickStr[2];
            unkey = quickStr[0] + " " + quickStr[1] + " " + "released" + " " + quickStr[2];
        }
        ShortcutKey.addNewShortcutKey(screenName, key);
        ShortcutKey.addNewShortcutKey("unspiltScrean_" + screenName, unkey);
        screenName = null;
        quickStr = new String[3];
        quickkey.setText("");
    }

    public void addNewScreenSpilt() {//tianjia zidingyi fenping
        WindowStatus ws = ScreenCtrlLinux.getSelectWindowStatusStatic();
        if (ws.getDesk().compareTo("-1") != 0)
            selectWindows.add(ws);
    }

    public void addPersonalizations() {//querenzidingyifenping
        if (selectWindows.size() == 0)
            return;
        ArrayList<AppFrame> af = new ArrayList<AppFrame>();
        for (int i = 0; i < selectWindows.size(); i++) {
            af.add(new AppFrame(Double.parseDouble(selectWindows.get(i).getX()), Double.parseDouble(selectWindows.get(i).getY())
                    , Double.parseDouble(selectWindows.get(i).getWidth()), Double.parseDouble(selectWindows.get(i).getHeight())));
        }
        String name = "spiltScrean_" + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254))
                + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254))
                + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254))
                + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254)) + String.valueOf((char) (Math.random() * 254));
        screenNameList.add(name);
        File file = new File(Path + "spiltScreenRecord.txt");
        try {
            PrintStream ps = new PrintStream(file);
            ps.println(screenNameList.size());
            for (int i = 0; i < screenNameList.size(); i++) {
                ps.println(screenNameList.get(i));
            }
            ps.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            CantSee.DrawImage(Path, name, af);
            CantSee.CreateScreenFile(Path, name, af);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ScreenSpilt ssp0 = new ScreenSpilt(name);
        autoGridPane.getChildren().add(ssp0);
        selectWindows.clear();
    }


    public void addNewWindow(ActionEvent actionEvent) {
        Stage secondStage = new Stage();
        Button bu1 = new Button("选择窗口");
        Button bu2 = new Button("完成");
        Label labbel = new Label("            ");

        HBox hbox = new HBox();
        hbox.getChildren().addAll(bu1, labbel, bu2);
        bu1.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                WindowStatus ws = ScreenCtrlLinux.getSelectWindowStatusStatic();
                if (ws.getDesk().compareTo("-1") != 0)
                    selectWindows.add(ws);
            }
        });
        bu2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                if (selectWindows.size() == 0)
                    return;
                ArrayList<AppFrame> af = new ArrayList<AppFrame>();
                for (int i = 0; i < selectWindows.size(); i++) {
                    af.add(new AppFrame(Double.valueOf(selectWindows.get(i).getX()), Double.valueOf(selectWindows.get(i).getY())
                            , Double.valueOf(selectWindows.get(i).getWidth()), Double.valueOf(selectWindows.get(i).getHeight())));
                }
                String name = "spiltScrean_" + String.valueOf(Math.random() * 100 + 2) + String.valueOf(Math.random() * 100 + 2) + String.valueOf(Math.random() * 100 + 2)
                        + String.valueOf(Math.random() * 100 + 2);
                screenNameList.add(name);
                File file = new File(Path + "spiltScreenRecord.txt");
                try {
                    PrintStream ps = new PrintStream(file);
                    ps.println(screenNameList.size());
                    for (int i = 0; i < screenNameList.size(); i++) {
                        ps.println(screenNameList.get(i));
                    }
                    ps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    CantSee.DrawImage(Path, name, af);
                    CantSee.CreateScreenFile(Path, name, af);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                adaption(name);

                selectWindows.clear();
            }
        });
        Scene secondeScene = new Scene(hbox, 300, 200);
        secondStage.setScene(secondeScene);
        secondeScene.getStylesheets().add(getClass().getResource("/useless/wallpaper.css").toExternalForm());
        labbel.setStyle("-fx-background-color: TRANSPARTENT;");
        hbox.setStyle("-fx-padding: 50 10 30 40 ;");
        secondStage.initModality(Modality.APPLICATION_MODAL);
        secondStage.show();
    }

    public void addNewSpiltScreen(ActionEvent actionEvent) {
        CantSee.adapteScreen();
        ArrayList<AppFrame> af = new ArrayList<AppFrame>();
        List<WindowStatus> windowList;
        windowList = ScreenCtrlLinux.getAllWindowStatusStatic();
        for (int i = 0; i < windowList.size(); i++) {
            if (windowList.get(i).getDesk().compareTo("-1") != 0 && windowList.get(i).getWindowState().compareTo("Hidden") != 0 && windowList.get(i).getName().compareTo("画屏") != 0) {
                af.add(new AppFrame(Double.valueOf(windowList.get(i).getX()) / CantSee.getScreenRectangle().getWidth() * 1920,
                        Double.valueOf(windowList.get(i).getY()) / CantSee.getScreenRectangle().getHeight() * 1080,
                        Double.valueOf(windowList.get(i).getWidth()) / CantSee.getScreenRectangle().getWidth() * 1920,
                        Double.valueOf(windowList.get(i).getHeight()) / CantSee.getScreenRectangle().getHeight() * 1080));
            }
        }
        String name = "spiltScrean_" + String.valueOf(Math.random() * 100 + 2) + String.valueOf(Math.random() * 100 + 2) + String.valueOf(Math.random() * 100 + 2)
                + String.valueOf(Math.random() * 100 + 2);
        screenNameList.add(name);
        File file = new File(Path + "spiltScreenRecord.txt");
        try {
            PrintStream ps = new PrintStream(file);
            ps.println(screenNameList.size());
            for (int i = 0; i < screenNameList.size(); i++) {
                ps.println(screenNameList.get(i));
            }
            ps.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            CantSee.DrawImage(Path, name, af);
            CantSee.CreateScreenFile(Path, name, af);
        } catch (Exception e) {
            e.printStackTrace();
        }

        adaption(name);
    }

    //自适应函数，新增自定义函数时让网格布局拓展的函数
    private void adaption(String name) {
        ScreenSpilt sspi = new ScreenSpilt(name);
        autoGridPane.getChildren().add(sspi);
        addScreenSpiltRightListener(sspi);
        flag++;
    }

    private void addScreenSpiltRightListener(ScreenSpilt screenSpilt){
        screenSpilt.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                if(mouseEvent.getButton().compareTo(MouseButton.SECONDARY) == 0){
                    if(screenName != screenSpilt.getId()){
                        if(screenSpilt.settingIt != null){
                            if(screenSpilt.settingIt.selected){
                                screenSpilt.settingIt.setStyle("-fx-background-color: rgb(106,255,169,255)");
                            }else{
                                screenSpilt.settingIt.setStyle("-fx-background-color: rgba(176 ,226, 255,.8);" +
                                        "    -fx-opacity: 0.8;"+"-fx-background-radius: 10;" +
                                        "    -fx-border-radius: 10;" +
                                        "    -fx-border-width: 1;");
                            }
                            screenSpilt.settingIt.setting = false;
                        }
                        screenName = screenSpilt.getId();
                        if(screenSpilt.selected){
                            screenSpilt.setStyle("-fx-background-color: linear-gradient(to right, #ef651e, #e49a1e, #d2c71e, #b6f11f)");
                        }else{
                            screenSpilt.setStyle("-fx-background-color: rgb(250,170,71)");
                        }

                        screenSpilt.setting = true;
                        screenSpilt.settingIt = screenSpilt;
                        String shortcutKey = getShortcutKey(screenSpilt);
                        if(shortcutKey == null){
                            quickkey.setPromptText("点击设置快捷键");
                        }else{
                            quickkey.setPromptText(shortcutKey);
                        }
                    }else{
                        screenSpilt.setting = false;
                        Controller.screenName = null;
                        quickkey.setPromptText("");
                        if(screenSpilt.selected){
                            screenSpilt.setStyle("-fx-background-color: rgb(106,255,169,255)");
                        }else{
                            screenSpilt.setStyle("-fx-background-color: rgba(176 ,226, 255,.8);" +
                                    "    -fx-opacity: 0.8;"+"-fx-background-radius: 10;" +
                                    "    -fx-border-radius: 10;" +
                                    "    -fx-border-width: 1;");
                        }
                    }
                }
            }
        });
    }

    private String getShortcutKey(ScreenSpilt screenSpilt){
        JSONArray shortcutKeyList = ShortcutKey.shortcutKeyList;
        for(int i = 0;i < shortcutKeyList.size();i ++){
            JSONObject shortcutKey = (JSONObject)shortcutKeyList.get(i);
            if(String.valueOf(shortcutKey.get("object")).compareTo(screenSpilt.getId()) == 0){
                return shortcutKey.getString("key").replace("pressed", "+");
            }
        }
        return null;
    }

    public void deleteSpiltScreen() {
        int adaption = 0;
        int size = autoGridPane.getChildren().size();
        for (int i = 0; i < size; i++) {
            ScreenSpilt scsp = (ScreenSpilt) autoGridPane.getChildren().get(i - adaption);
            if (scsp.selected) {
                ShortcutKey.deleteShortcutKey(scsp.getId());
                CantSee.deleteScreenInfo(Path, scsp.getId());
                screenNameList.remove(scsp.getId());
                autoGridPane.getChildren().remove(i - adaption);
                adaption++;
            }
        }
        String path = Path + "spiltScreenRecord.txt";
        File file = new File(path);
        try {
            PrintStream ps = new PrintStream(file);
            ps.println(screenNameList.size());
            for (int i = 0; i < screenNameList.size(); i++) {
                ps.println(screenNameList.get(i));
            }
            ps.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void errorWindow(MouseEvent MouseEvent) {
        Stage thirdStage = new Stage();
        Label labeeel = new Label("该Linux内核版本不匹配!");
        HBox hbbox = new HBox();
        hbbox.getChildren().add(labeeel);
        hbbox.setAlignment(Pos.CENTER);
        Scene thirdScene = new Scene(hbbox, 300, 200);
        thirdStage.setScene(thirdScene);
        thirdScene.getStylesheets().add(getClass().getResource("/useless/wallpaper.css").toExternalForm());
        labeeel.setStyle("-fx-text-fill:linear-gradient(to right, rgba(135 ,206, 250, .9), rgba(255 ,228 ,225, .9),rgba(132, 112, 255, .6),  rgba(240 ,255 ,240, .9));" + "-fx-font-size: 20px;");
        hbbox.setStyle("-fx-padding: 30 10 20 40 ;");
        thirdStage.initModality(Modality.APPLICATION_MODAL);
        thirdStage.show();

    }
}
